import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { getToken } from '@/utils/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/moments',
    component: () => import('@/modules/moments/views/index.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'MomentsList',
        component: () => import('@/modules/moments/views/Main.vue'),
      },
      {
        path: 'create',
        name: 'MomentsCreate',
        component: () => import('@/modules/moments/views/Form.vue'),
      },
      {
        path: ':id',
        name: 'MomentsDetail',
        component: () => import('@/modules/moments/views/Detail.vue'),
      },
    ],
  },
  {
    path: '/todo',
    component: () => import('@/modules/todo/views/index.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'TodoList',
        component: () => import('@/modules/todo/views/Main.vue'),
      },
      {
        path: ':id',
        name: 'TodoDetail',
        component: () => import('@/modules/todo/views/Detail.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫：检查登录状态
router.beforeEach((to, _from, next) => {
  const token = getToken()

  // 如果需要登录且没有 token，跳转到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    // 如果已登录访问登录页，跳转到首页
    next('/home')
  } else {
    next()
  }
})

export default router
